const { Op } = require('sequelize');
const Job = require('../models/job');
const Company = require('../models/company');

// 多条件查询职位
exports.getJobs = async (req, res) => {
  try {
    const { keyword, industry, location, salaryRange, experience, jobType } = req.query;
    const whereClause = {};

    // 构建查询条件
    if (keyword) {
      whereClause[Op.or] = [
        { title: { [Op.like]: `%${keyword}%` } },
        { description: { [Op.like]: `%${keyword}%` } }
      ];
    }
    if (industry) whereClause.industry = industry;
    if (location) whereClause.location = location;
    if (salaryRange) whereClause.salaryRange = salaryRange;
    if (experience) whereClause.experience = experience;
    if (jobType) whereClause.jobType = jobType;

    // 执行查询并关联公司信息
    const jobs = await Job.findAll({
      where: whereClause,
      include: [{
        model: Company,
        attributes: ['id', 'name', 'logo']
      }],
      order: [['createdAt', 'DESC']]
    });

    res.status(200).json(jobs);
  } catch (error) {
    console.error('职位查询失败:', error);
    res.status(500).json({ message: '服务器错误，查询职位失败' });
  }
};

// 获取职位详情
exports.getJobById = async (req, res) => {
  try {
    const job = await Job.findByPk(req.params.id, {
      include: [{
        model: Company,
        attributes: ['id', 'name', 'description', 'logo']
      }]
    });

    if (!job) {
      return res.status(404).json({ message: '职位不存在' });
    }

    res.status(200).json(job);
  } catch (error) {
    console.error('获取职位详情失败:', error);
    res.status(500).json({ message: '服务器错误，获取职位详情失败' });
  }
};